﻿'use strict';

define([
    'backbone',
], function (Backbone) {
    return Backbone.Router.extend({
        currentView: null,
        mainViewContainer: null,
        views: {},

        initialize: function (mainViewContainerRef) {
            var that = this;

            this.mainViewContainer = $(mainViewContainerRef);

            // All navigation that is relative should be passed through the navigate
            // method, to be processed by the router. If the link has a `data-bypass`
            // attribute, bypass the delegation completely.
            $(document).on('click', 'a[href]:not([data-bypass])', function (evt) {
                evt.preventDefault();

                // `Backbone.history.navigate` is sufficient for all Routers and will
                // trigger the correct events. The Router's internal `navigate` method
                // calls this anyways.  The fragment is sliced from the root.
                that.route($(this).attr('href'), true);
            });

            return this;
        },
        route: function (route, name, callback) {
            this._switchView(route, name, callback);
            this.navigate(route);

            if (callback)
                callback();

            return this;
        },
        _switchView: function (route, name, callback) {
            var that = this
                , viewModuleName = 'screens/' + route + '/view'
                , modelModuleName = 'screens/' + route + '/model'
                , fn = function (viewCtr, modelCtr) {
                    var view;

                    if (that.views[route] == null) {
                        view = new viewCtr({
                            id: route,
                            model: new modelCtr(),
                        });

                        that.views[route] = view;

                        view.$el.hide();

                        that.mainViewContainer.append(view.el);

                        if (that.currentView == null)
                            that.currentView = view;

                        that.currentView.render();
                    }
                    else {
                        view = that.views[route];
                    }

                    that.currentView.$el.hide();

                    that.currentView = view;

                    that.currentView.$el.show();
                };

            require([viewModuleName, modelModuleName], fn);

            return this;
        },
    });
});